package handler

import (
	"net/http"

	"zeroweb/web/internal/logic"
	"zeroweb/web/internal/svc"
	"zeroweb/web/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func WebHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.Request
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewWebLogic(r.Context(), svcCtx)
		resp, err := l.Web(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

// 自定义
func MyHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		httpx.OkJsonCtx(r.Context(), w, "hello")
	}
}

// 返回短文
func ArticleController() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		//定义结构体
		type Article struct {
			Str string
		}
		art := Article{
			"开发者可以使用http.ResponseWriter元素返回参数，也可以使用httpx提供的方法返回数据。后者的优势是可以直接返回结构体不用在序列化操作。",
		}
		httpx.OkJson(w, art)
	}
}
